import mysql.connector,os,shutil,requests
from tkinter import messagebox
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO

def file_download(url,pic,path):
    response = requests.get(url)
    if response.status_code == 200:
        image_content = response.content
        save_path = path+'/'+pic
        with open(save_path, 'wb') as file:
            file.write(image_content)
            return True
    else:
        return False
        
def task_query(username,role):
    mydb = mysql.connector.connect(host="43.161.240.94",user="hcecpod_com",passwd="Xcd9sMZ9DMBBkbMf",database="hcecpod_com")
    mycursor = mydb.cursor()
    mycursor.execute("select task_id,sort from task_draw where `status`='画图中' and drawer='"+username+"' order by sort asc")
    myresult = mycursor.fetchall()
    if myresult:
        temp_list=[]
        for x in myresult:
            temp_list.append(x[1]+'-'+x[0])
        draw_str="您有"+str(len(temp_list))+"个画图任务："
        draw_str+=','.join(temp_list)
    else:
        draw_str="您没有画图任务"
        
    mycursor.execute("select task_id,sort from task_design where `status`='P图中' and `sort`='上架P图' and designer='"+username+"' order by sort asc")
    myresult = mycursor.fetchall()
    if myresult:
        temp_list=[]
        for x in myresult:
            temp_list.append(x[1]+'-'+x[0])
        design_str="您有"+str(len(temp_list))+"个P图任务："
        design_str+=','.join(temp_list)
    else:
        design_str="您没有P图任务"
    return (draw_str+'\n'+design_str+'\n')

def task_files_copy(username,role):    
    mydb = mysql.connector.connect(host="43.161.240.94",user="hcecpod_com",passwd="Xcd9sMZ9DMBBkbMf",database="hcecpod_com")
    mycursor = mydb.cursor()
    # 绘图
    result_draw={'task':0,'moved':0,'fail':0}
    mycursor.execute("select task_id,connect_id from task_draw where `status`='画图中' and drawer='"+username+"'")
    myresult = mycursor.fetchall()
    if myresult:
        for x in myresult:
            path1="D:/work/绘图/doing/"+x[0]
            if not os.path.exists(path1):
                os.makedirs(path1)
            result_draw['task']+=1
            mycursor.execute("select refer_pic,draw_pic from task_draw where `connect_id`='"+x[1]+"'")
            pic_result= mycursor.fetchall()
            for y in pic_result:
                print(y)
                if y[0]:
                    url1="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/"+y[0]
                    new_file=y[0].split('/')[-1]
                    if(file_download(url1,new_file,path1)):
                        result_draw['moved']+=1
                    else:
                        result_draw['fail']+=1
                if y[1]:
                    url1="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/draw/"+y[1]
                    new_file=y[1]
                    if(file_download(url1,new_file,path1)):
                        result_draw['moved']+=1
                    else:
                        result_draw['fail']+=1
    str1="COPY绘图任务："+str(result_draw['task'])+"个，成功COPY文件："+str(result_draw['moved'])+"个，COPY失败："+str(result_draw['fail'])+"个"
    # P图
    result_draw={'task':0,'moved':0,'fail':0}
    mycursor.execute("select operater_num,oc_id,model,pattern,`pic` from data_choose where oc_id in (select connect_id from task_design where `status`='P图中' and designer='"+username+"' and `sort`='上架P图')")
    myresult = mycursor.fetchall()
    if myresult:
        for x in myresult:
            path1="D:/work/美工/doing/"+x[0]
            if not os.path.exists(path1):
                os.makedirs(path1)
            result_draw['task']+=1
            # 下载模特图
            url1="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/model/"+x[2]
            new_name=x[1]+'#'+x[2]
            if(file_download(url1,new_name,path1)):
                result_draw['moved']+=1
            else:
                result_draw['fail']+=1
             # 下载细节图
            mycursor.execute("select style_name from data_model where pic ='"+x[2]+"'")
            style_name = mycursor.fetchone()[0]
            if(style_name):
                mycursor.execute("select pic from data_pingpu where style_name ='"+style_name+"'")
                myresult2=mycursor.fetchall()
                if(myresult2):
                    temp_num=1
                    for y in myresult2:
                        url2="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/pingpu/"+y[0]
                        temp_name='平铺'+str(temp_num)+'.'+y[0].split('.')[-1]
                        if(file_download(url2,temp_name,path1)):
                            result_draw['moved']+=1
                        else:
                            result_draw['fail']+=1
                        temp_num+=1                
            # 下载设计图                
            url2="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/choose/"+x[4]
            new_name2=x[4]
            print(url2)
            if(file_download(url2,new_name2,path1)):
                result_draw['moved']+=1
            else:
                result_draw['fail']+=1
            pics=x[3].split('&')
            # 下载烫画稿
            for pic in pics:
                if 'png' in pic:
                    if(pic_add_size_download(x[1],pic,path1)):
                        result_draw['moved']+=1
                    else:
                        result_draw['fail']+=1
                        
    str2="COPY美工任务："+str(result_draw['task'])+"个，成功COPY文件："+str(result_draw['moved'])+"个，COPY失败："+str(result_draw['fail'])+"个"
    messagebox.showinfo(title='Hi', message=str1+'\n'+str2)
def pic_add_size_download(oc_id,pattern,path):
    if 'TK' in pattern:
        url = "https://hcecpod-1343049753.cos.accelerate.myqcloud.com/pattern/" + pattern
    else:
        url = "https://hcecpod-1343049753.cos.accelerate.myqcloud.com/draw/" + pattern
    response = requests.get(url)
    response.raise_for_status()
    img = Image.open(BytesIO(response.content))
    width, height = img.size
    
    mydb = mysql.connector.connect(host="43.161.240.94",user="hcecpod_com",passwd="Xcd9sMZ9DMBBkbMf",database="hcecpod_com")
    mycursor = mydb.cursor()
    mycursor.execute("select width from data_choose_pattern_size where oc_id='"+oc_id+"' and pattern='"+pattern+"'")
    myresult = mycursor.fetchone()
    if myresult:        
        try:            
            text_width=myresult[0]            
            text_height = round(height * text_width / width,2)
            text_size='宽度：'+str(text_width)+'CM   高度：'+str(text_height)+'CM'
            print(text_size)
        except:
            text_size='尺寸设置有误，请联系乔月'
            print('BUG WRONG TABLE')            
    else:
        text_size='未作尺寸设置，请联系画图设计作标注'
        print(pattern,'BUG DATA NOT IN TALBE')

    image = Image.new('RGBA', (3000, 250), (0, 0, 0, 0))
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("msyhbd.ttc", 120)
    draw.text((846,50), text_size, fill=(0,0,0), font=font)

    try:        
        new_image = Image.new('RGBA', (max(img.width, image.width), img.height + image.height))
        new_image.paste(img, (0, 0))
        new_image.paste(image, (0, img.height))
        new_image.save(path+'/'+oc_id+'#'+pattern)
        return True
    except:
        return False
    
# task_files_copy('乔月','画图')      
def over_task_submit(username,role):
    messagebox.showinfo(title='Hi', message="该模块缺乏必要性")
